<template>
	<div class="app-container">
		<div ref="box1" class="total-box">
			<div class="total-item">
				<div class="total-title">IOT当班总产量(kg)</div>
				<div class="total-val">{{ tableHeaderData.iotKgSum || 0 }}</div>
			</div>
			<div class="total-item">
				<div class="total-title">班次机台总产量(kg)</div>
				<div class="total-val">{{ tableHeaderData.outputKgSum || 0 }}</div>
			</div>
			<div class="total-item">
				<div class="total-title">报工总产量(kg)</div>
				<div class="total-val">{{ tableHeaderData.reportKgSum || 0 }}</div>
			</div>
			<div class="total-item">
				<div class="total-title">报工与IOT差异</div>
				<div class="total-val">{{ Number(tableHeaderData.iotDiffReportSum ? tableHeaderData.iotDiffReportSum.slice(0, -1) : 0).toFixed(2) || 0 }}%</div>
			</div>
			<div class="total-item">
				<div class="total-title">班次机台与IOT差异</div>
				<div class="total-val">{{ Number(tableHeaderData.iotDiffOutputSum ? tableHeaderData.iotDiffOutputSum.slice(0, -1) : 0).toFixed(2) || 0 }}%</div>
			</div>
			<div class="total-item">
				<div class="total-title">班次机台与报工差异</div>
				<div class="total-val">{{ Number(tableHeaderData.outputDiffReportSum ? tableHeaderData.outputDiffReportSum.slice(0, -1) : 0).toFixed(2) || 0 }}%</div>
			</div>
		</div>
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<div><el-button type="warning" class="item-gap" size="small" :loading="exportLoading" @click="onReportBtn">导出</el-button></div>
				</div>
				<div class="flex-end-center-wrap">
					<jk-date-picker v-model="searchParams.belongDate" size="small" :clearable="false" placeholder="选择日期" class="search-bar-item-size2 item-gap"></jk-date-picker>
					<jk-select v-model="searchParams.workshopId" clearable placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-select v-model="searchParams.processCode" value-key-name="code" :option-list="garbledProcess" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.shiftId" :option-list="shiftList" clearable placeholder="班次" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.machineCode" placeholder="设备编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @change="onSearchBtn" @keyup.enter.native="onSearchBtn" />
					<jk-search-button :loading="tableLoading" class="" @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<component
				:is="viewType"
				ref="exportTotalUse"
				:table-column-list="tableColumnList"
				:loading="tableLoading"
				:search-params="searchParams"
				:table-data="tableData"
				:height="tableHeight - 50"
				@getListRequest="getListRequest"
			></component>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, pageConfig, formatTime } from '/src/utils/jk/jk-tool';
    import permissionMixin from '../../../mixins/permission-mixin';
    import listView from './components/list-view';
    import chartView from './components/chart-view';
    import { workforcemanagementShiftPage } from '@/api/schedule/shift';
    import scheduleShift from '../../statisticAnalysis/scheduleShiftProductionReport/scheduleShift';
    import { productionCheckOutputReportPage } from '../../../api/production/reports';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import { workforceManagementShiftGetByTime } from '../../../api/schedule/shift';
    export default {
        name: 'ScheduleShiftProductionReportRecord',
        mixins: [permissionMixin, calHeight, scheduleShift, getMenuColumn],
        components: {
            listView,
            chartView
        },
        data() {
            return {
                totalCount: 0,
                tableColumnList: [],
                prefix: '',
                viewType: 'listView',
                processList: [],
                workshopList: [],
                garbledProcess: [],
                shiftList: [],
                dataId: null,
                tableLoading: false,
                exportLoading: false,
                tableData: [],
                tableHeaderData: {},
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: 500,
                    machineCode: null,
                    processCode: '',
                    belongDate: '',
                    shiftId: '',
                    workshopId: null
                }
            };
        },
        methods: {
            onPage(e, size) {
                this.searchParams.pageNo = e;
                this.searchParams.pageSize = size;
                this.getListRequest();
            },
            /** 查询列表 */
            getListRequest() {
                if (!this.searchParams.belongDate) return;
                this.tableLoading = true;
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                const shiftItem = this.shiftList.find(x => x.id === params.shiftId) || {};
                params.shiftCode = shiftItem.code;
                productionCheckOutputReportPage(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res.tableData;
                        this.tableHeaderData = res.data.res.tableHeader;
                        this.totalCount = res.data.count;
                    }
                });
            },
            onWorkshopChange(val) {
                this.$set(this.searchParams, 'shiftId', '');
                this.$set(this.searchParams, 'processCode', '');
                if (!this.searchParams.workshopId) {
                    this.shiftList = [];
                    this.garbledProcess = [];
                } else {
                    this.getShiftListRequest();
                    this.getProcessData(val);
                }
            },
            getProcessData(val) {
                this.garbledProcess = [];
                this.processList.forEach(y => {
                    if (val === y.workshopId) {
                        this.garbledProcess.push(y);
                    }
                });
            },
            getCurrentShiftInfoRequest() {
                if (!this.searchParams.workshopId) return;
                const currentTime = formatTime(Date.now());
                const currentHMS = currentTime && currentTime.split(' ').length ? currentTime.split(' ')[1] : '';
                return workforceManagementShiftGetByTime({
                    workshopId: this.searchParams.workshopId,
                    belongTime: `${this.searchParams.belongDate} ${currentHMS}`
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        // 默认上一班次
                        this.$set(this.searchParams, 'belongDate', resData.lastShiftInfo ? resData.lastShiftInfo.belongDate : '');
                        this.$set(this.searchParams, 'shiftId', resData.lastShiftInfo ? resData.lastShiftInfo.id : null);
                    }
                });
            },
            // 获取所有班次
            getShiftListRequest() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                delete params.shiftId;
                delete params.yarnCount;
                delete params.processCode;
                params.auditState = 1;
                return workforcemanagementShiftPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.getListRequest();
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                const shiftItem = this.shiftList.find(x => x.id === params.shiftId) || {};
                params.shiftCode = shiftItem.code;
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    this.exportLoading = false;
                    return productionCheckOutputReportPage(params).then(res => {
                        if (res.data.status === 200) {
              import('@/vendor/Export2Excel').then(excel => {
                const tHeader = this.tableColumnList.map(x => x.title);
                const filterVal = this.tableColumnList.map(x => x.keyName);
                const list = JSON.parse(JSON.stringify(res.data.res.tableData)).map(item => {
                  return item;
                });
                // 合计项
                const totalItem = {};
                filterVal.forEach((x, idx) => {
                  totalItem[x] = this.$refs.exportTotalUse.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0][idx];
                });
                list.push(totalItem);
                const data = list.map(v => filterVal.map(j => {
                  return v[j];
                }));
                excel.export_json_to_excel({
                  header: tHeader,
                  data,
                  filename: `${this.$route.meta.title}`,
                  autoWidth: true,
                  bookType: 'xlsx'
                });
              });
                        }
                    });
                }).catch(() => {});
            },
            async getDependentData() {
                this.processList = this.$store.state.user.userProcess.processList;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                await this.getMenuColumnListRequest();
                this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                if (!this.searchParams.workshopId) {
                    this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                if (!this.searchParams.processCode) {
                    this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || '');
                }
                await this.getShiftListRequest();
                await this.getCurrentShiftInfoRequest();
                this.getProcessData(this.$store.state.user.userWorkshop.defaultWorkshopId);
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style scoped lang="scss">
.size {
    font-size: 14px;
    margin-left: 3px;
}
.total-box {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    .total-item {
        width: 160px;
        height: 70px;
        background: #fff;
        border: solid 1px #eee;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        margin: 0 5px;
        border-radius: 10px;
        box-shadow: 0 0 2px 1px #eee;
        .total-title {
            color: #808695;
            font-size: 16px;
        }
        .total-val {
            font-size: 18px;
            color: #515a6e;
            margin-top: 2px;
        }
    }
    .total-item:hover {
        box-shadow: 0 0 2px 1px #eee;
    }
}

</style>
